/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.formserver.vmmanager;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.inspur.edp.das.commonmodel.IGspCommonModel;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.exception.ViewModelException;
import com.inspur.edp.formserver.viewmodel.json.model.ViewModelDeserializer;
import com.inspur.edp.formserver.viewmodel.json.model.ViewModelSerializer;
import com.inspur.edp.formserver.vmmanager.exception.VoManagerErrorCodes;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.spi.MetadataTransferSerializer;

public class TransferSerializer implements MetadataTransferSerializer {


    //region getMapper

    private ObjectMapper getMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(IGspCommonModel.class, new ViewModelDeserializer());
        module.addSerializer(IGspCommonModel.class, new ViewModelSerializer());
        mapper.registerModule(module);
        return mapper;
    }

    //endregion

    //region 序列化
    public final String serialize(IMetadataContent metadataContent) {
        GspViewModel viewModel = (GspViewModel) ((metadataContent instanceof GspViewModel) ? metadataContent : null);
        String modelJson;
        try {
            modelJson = getMapper().writeValueAsString(viewModel);
        } catch (JsonProcessingException e) {
            throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0096, e);
        }
        return modelJson;
    }

    public final IMetadataContent deserialize(String contentString) {
        GspViewModel viewModel;
        try {
            viewModel = getMapper().readValue(contentString, GspViewModel.class);
        } catch (JsonProcessingException e) {
            throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0097, e);

        }
        return viewModel;
    }
}
